package com.example.a2032.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.example.a2032.livedatas.SingleSourceLiveData
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMConversation
import com.hyphenate.easeui.modules.conversation.model.EaseConversationInfo
import java.util.*

class UnreadMsgViewModel(application: Application) : AndroidViewModel(application) {
    var unReadList: SingleSourceLiveData<MutableList<EMConversation>>? = null
    var liveData: MutableLiveData<MutableList<EMConversation>>? = null

    init {
        unReadList = SingleSourceLiveData<MutableList<EMConversation>>()
        liveData = MutableLiveData()
        unReadList?.setSource(liveData)
    }

    fun getUnReadList() {
        val map = EMClient.getInstance().chatManager().allConversations
        val unreadList: MutableList<EMConversation> = ArrayList()
        map.filter {
            it.value.unreadMsgCount != 0
        }.forEach {
            unreadList.add(it.value)
        };
        sortByTimestamp(unreadList)
        liveData?.postValue(unreadList)
    }

    private fun sortByTimestamp(list: List<EMConversation>?) {
        if (list == null || list.isEmpty()) {
            return
        }
        Collections.sort(list) { o1, o2 ->
            when {
                o2!!.lastMessage.msgTime > o1!!.lastMessage.msgTime -> {
                    1
                }
                o2.lastMessage.msgTime == o1.lastMessage.msgTime -> {
                    0
                }
                else -> {
                    -1
                }
            }
        }
    }

}